const http = require('http')
const path = require('path')
const fs = require('fs')
const mime = require('mime')
const server = http.createServer((req, res) => {
    let filePath = path.resolve(__dirname, path.join('www', req.url))
    if (fs.existsSync(filePath)) {
        const stats = fs.statSync(filePath)
        const isDir = stats.isDirectory()
        if (isDir) {
            filePath = path.join(filePath, 'index.html')
        }
        //读取资源
        const content = fs.readFileSync(filePath)
        //获取文件的扩展名
        const { ext } = path.parse(filePath)
        res.writeHead(200, { 'Content-Type': mime.getType(ext) })
        res.end(content)
    } else {
        res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' })
        res.end('<h1>404 not found</h1>')
    }
})
server.listen(8080, () => {
    console.log('server is running at http://127.0.0.1:8080')
})
